from flask import Flask, request, jsonify
from flask_cors import CORS
from webrtc_handler import WebRTCHandler

app = Flask(__name__)
CORS(app, resources={
    r"/offer": {"origins": "http://localhost:5173"},
    r"/answer": {"origins": "http://localhost:5173"},
    r"/ice": {"origins": "http://localhost:5173"},
    r"/room/*": {"origins": "http://localhost:5173"}
})
webrtc_handler = WebRTCHandler()

@app.route('/room/create', methods=['POST'])
def create_room():
    """创建新房间"""
    room_id, user_id = webrtc_handler.create_or_join_room()
    return jsonify({
        'status': 'room_created',
        'room_id': room_id,
        'user_id': user_id
    })

@app.route('/room/join', methods=['POST'])
def join_room():
    """加入现有房间"""
    data = request.json
    if not data or 'room_id' not in data:
        return jsonify({'error': 'Room ID is required'}), 400
        
    room_id, user_id = webrtc_handler.create_or_join_room(data['room_id'])
    return jsonify({
        'status': 'room_joined',
        'room_id': room_id,
        'user_id': user_id
    })

@app.route('/room/<room_id>/peers', methods=['GET'])
def get_room_peers(room_id):
    """获取房间内所有用户"""
    peers = webrtc_handler.get_room_peers(room_id)
    return jsonify({
        'room_id': room_id,
        'peers': list(peers.keys())
    })

@app.route('/room/leave', methods=['POST'])
def leave_room():
    """离开房间"""
    data = request.json
    if not data or 'user_id' not in data or 'room_id' not in data:
        return jsonify({'error': 'User ID and Room ID are required'}), 400
        
    result = webrtc_handler.leave_room(data['user_id'], data['room_id'])
    return jsonify(result)

@app.route('/offer', methods=['POST'])
def handle_offer():
    data = request.json
    if not data or 'offer' not in data or 'user_id' not in data or 'room_id' not in data:
        return jsonify({'error': 'Missing required fields (offer, user_id, room_id)'}), 400
    
    if not isinstance(data['offer'], dict) or 'sdp' not in data['offer'] or 'type' not in data['offer']:
        return jsonify({'error': 'Invalid offer format'}), 400
    
    result = webrtc_handler.handle_offer({
        'offer': data['offer'],
        'user_id': data['user_id'],
        'room_id': data['room_id']
    })
    return jsonify(result)

@app.route('/answer', methods=['POST'])
def handle_answer():
    data = request.json
    if not data or 'answer' not in data or 'user_id' not in data or 'room_id' not in data:
        return jsonify({'error': 'Missing required fields (answer, user_id, room_id)'}), 400
    
    answer = data['answer']
    if not isinstance(answer, dict) or 'sdp' not in answer or 'type' not in answer:
        return jsonify({'error': 'Invalid answer format'}), 400
    
    result = webrtc_handler.handle_answer({
        'answer': answer,
        'user_id': data['user_id'],
        'room_id': data['room_id']
    })
    return jsonify(result)

@app.route('/ice', methods=['POST'])
def handle_ice_candidate():
    data = request.json
    if not data or 'candidate' not in data or 'user_id' not in data or 'room_id' not in data:
        return jsonify({'error': 'Missing required fields (candidate, user_id, room_id)'}), 400
    
    candidate = data['candidate']
    if not isinstance(candidate, dict) or 'candidate' not in candidate or 'sdpMid' not in candidate or 'sdpMLineIndex' not in candidate:
        return jsonify({'error': 'Invalid ICE candidate format'}), 400
    
    result = webrtc_handler.handle_ice_candidate({
        'candidate': candidate,
        'user_id': data['user_id'],
        'room_id': data['room_id']
    })
    return jsonify(result)

@app.route('/room/<room_id>/offers', methods=['GET'])
def get_offers(room_id):
    offers = webrtc_handler.get_room_offers(room_id)
    return jsonify(offers)

@app.route('/room/<room_id>/answers', methods=['GET'])
def get_answers(room_id):
    answers = webrtc_handler.get_room_answers(room_id)
    return jsonify(answers)

@app.route('/room/<room_id>/candidates', methods=['GET'])
def get_candidates(room_id):
    candidates = webrtc_handler.get_room_candidates(room_id)
    return jsonify(candidates)

@app.route('/connection/status/<user_id>', methods=['GET'])
def get_connection_status(user_id):
    """获取用户连接状态"""
    result = webrtc_handler.get_connection_status(user_id)
    return jsonify(result)

@app.route('/connection/established', methods=['POST'])
def mark_connection_established():
    """标记连接已建立"""
    data = request.json
    if not data or 'user_id' not in data or 'room_id' not in data:
        return jsonify({'error': 'Missing required fields (user_id, room_id)'}), 400
    
    result = webrtc_handler.mark_connection_established(data['user_id'], data['room_id'])
    return jsonify(result)

@app.route('/stats', methods=['GET'])
def get_server_stats():
    """获取服务器统计信息"""
    try:
        stats = webrtc_handler.get_stats()
        return jsonify(stats)
    except Exception as e:
        return jsonify({'error': f'获取统计信息失败: {str(e)}'}), 500

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': '接口不存在'}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({'error': '服务器内部错误'}), 500

@app.errorhandler(Exception)
def handle_exception(e):
    return jsonify({'error': f'未处理的异常: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)